import React, { useState, useEffect, memo } from 'react';
import { Link, useLocation, history } from 'umi';
import styles from './index.less';
import { Layout, Menu, Button, Dropdown, Modal } from 'antd';
import { UserOutlined } from '@ant-design/icons';
const { Header } = Layout;
const MenuItem = Menu.Item;
const Menus = [
  {
    name: '首页',
    key: '/dashboard',
  },
  {
    name: '用户',
    key: '/user',
  },
  {
    name: '日报',
    key: '/report',
  },
  {
    name: '动态页面',
    key: '/dynamic',
  },
  {
    name: '测试页面',
    key: '/test',
  },
  {
    name: 'mobx',
    key: '/mobx',
  },
  {
    name: 'table',
    key: '/table',
  },
  {
    name: 'tab-anchor',
    key: '/tabanchor',
  },
];
const MyHeader = () => {
  const [selectedKey, setSelectedKey] = useState<string>('/dashboard');
  // 当前路径
  const { pathname } = useLocation();
  console.log(useLocation());
  useEffect(() => {
    const key: string =
      pathname.length > 1 ? '/' + pathname.split('/')[1] : '/dashboard';
    console.log(key);
    setSelectedKey(key);
  }, [pathname]);

  const handleClick = (e: any) => {
    // console.log('1');
    setSelectedKey(e.key);
  };

  const handleLogout = () => {
    Modal.confirm({
      title: '温馨提示',
      content: '您确定要退出吗？',
      onOk() {
        sessionStorage.clear();
        history.replace('/login');
      },
    });
  };
  // 导航菜单
  // 箭头函数注意 () => {} 和 （） => 的区别
  const MemoMenu = memo(() => (
    <Menu
      className={styles.menu}
      onClick={handleClick}
      selectedKeys={[selectedKey]}
      theme="dark"
      mode="horizontal"
    >
      {Menus.map((item) => (
        <MenuItem key={item.key}>
          <Link to={item.key}>{item.name}</Link>
        </MenuItem>
      ))}
    </Menu>
  ));
  // const MemoMenu = memo (() => {
  //   console.log('render')
  //   return (
  //     <Menu
  //       onClick={handleClick}
  //       selectedKeys={[selectedKey]}
  //       theme="dark"
  //       mode="horizontal"
  //     >
  //       {Menus.map((item) => {
  //         return (
  //           <MenuItem key={item.key}>
  //             <Link to={item.key}>{item.name}</Link>
  //           </MenuItem>
  //         );
  //       })}
  //     </Menu>
  //   );
  // });
  // 下拉菜单
  const DropMenu = (
    <Menu>
      <MenuItem>
        <div onClick={handleLogout}>退出</div>
      </MenuItem>
    </Menu>
  );
  const MemoDropDown = memo(() => (
    <Dropdown overlay={DropMenu}>
      <div className={styles.dropBox}>
        <UserOutlined />
        <span className={styles.username}>admin</span>
      </div>
    </Dropdown>
  ));
  return (
    <>
      <Layout>
        <Header className={styles.header}>
          <img
            className={styles.logo}
            src={require('../../../assets/img/logo.png')}
            alt="logo"
          />
          {/*<div className="logo" />*/}
          <MemoMenu />
          <MemoDropDown />
        </Header>
      </Layout>
    </>
  );
};

export default MyHeader;
